﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using System.Diagnostics;
using SocialLotus.Entities;
using System.Reflection;
using SocialLotus.DAO;

namespace SocialLotus.DAO
{
    public class DAOSession : IDisposable
    {
        private static readonly object _padlock = new object();
        private ISession _nhSession;

        /// <summary>
        /// Initializes a new instance of the <see cref="DAOSession"/> class.
        /// </summary>
        public DAOSession()
        {
            Debug.WriteLine("DAOSession created");
            _nhSession = DAOFactory.Instance.GetSession();
        }

        /// <summary>
        /// Gets a DAO of the type T.
        /// </summary>
        /// <typeparam name="T">The DAO type.</typeparam>
        /// <returns>The DAO.</returns>
        public T GetDAO<T>() where T : BaseDAO
        {
            //cache created objects?
            return (T)typeof(T).InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, new object[] { _nhSession });
        }

        /// <summary>
        /// Gets a generic DAO instance.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public GenericDAO<T> GetGenericDAO<T>() where T : PersistedEntity
        {
            return new GenericDAO<T>(_nhSession);
        }

        public void Dispose()
        {
            Debug.WriteLine("DAOSession dispose");

            if (_nhSession != null)
            {
                if (_nhSession.IsOpen)
                {
                    //_nhSession.Flush();
                    _nhSession.Close();
                }

                _nhSession.Dispose();

                Debug.WriteLine("DAO Session closed");
            }
        }

        public void ClearChanges()
        {
            if (_nhSession != null)
            {
                _nhSession.Clear();
            }
        }

    }
}
